class Solution:
    def reverse(self, x: int) -> int:
        """
        反转 32 位有符号整数。

        处理溢出情况。
        """

        sign = -1 if x < 0 else 1
        x = abs(x)  # 处理负数，先取绝对值

        reversed_num = 0
        while x > 0:
            digit = x % 10
            x //= 10

            # 检查是否会溢出
            if reversed_num > 214748364 or (reversed_num == 214748364 and digit > 7):
                return 0

            reversed_num = reversed_num * 10 + digit

        return sign * reversed_num
